package com.aiphome.benchmark;

import com.aiphome.util.JwtUtils;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(value = 2)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
public class JwtPerformanceBenchmark {

    private JwtUtils jwtUtils;
    private Authentication authentication;
    private String testToken;

    @Setup
    public void setUp() {
        // 初始化JwtUtils
        jwtUtils = new JwtUtils();
        
        // 设置JwtUtils的私有字段
        try {
            // 设置jwtSecret
            java.lang.reflect.Field secretField = jwtUtils.getClass().getDeclaredField("jwtSecret");
            secretField.setAccessible(true);
            secretField.set(jwtUtils, "benchmark-secret-key-for-jwt-performance-testing");
            
            // 设置jwtExpirationMs
            java.lang.reflect.Field expirationField = jwtUtils.getClass().getDeclaredField("jwtExpirationMs");
            expirationField.setAccessible(true);
            expirationField.set(jwtUtils, 86400000); // 24小时
        } catch (Exception e) {
            throw new RuntimeException("Failed to set up JwtUtils for benchmarking", e);
        }
        
        // 创建测试用户和认证对象
        UserDetails userDetails = new User("benchmarkuser", "password", Collections.emptyList());
        authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        
        // 预先生成一个测试令牌用于验证测试
        testToken = jwtUtils.generateJwtToken(authentication);
    }

    @Benchmark
    public String generateJwtToken() {
        return jwtUtils.generateJwtToken(authentication);
    }

    @Benchmark
    public boolean validateJwtToken() {
        return jwtUtils.validateJwtToken(testToken);
    }

    @Benchmark
    public String getUsernameFromToken() {
        return jwtUtils.getUserNameFromJwtToken(testToken);
    }

    // 主方法用于直接运行基准测试
    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(JwtPerformanceBenchmark.class.getSimpleName())
                .build();
        new Runner(options).run();
    }
}